import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

public class O62 {
    public int lastRemaining(int n, int m) {
        int re = 0;
        for (int i = 2; i <= n; i++) {
            re = (re+m)%i;
        }
        return re;
    }
}
